package cn.shyouchi.wuguanjia.android.ui.attendance.report;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.attendance.AttendanceApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.ReportSubmitEvent;
import cn.shyouchi.wuguanjia.android.exception.ApiException;
import cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceTokePhotoActivity;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class StaffReportActivity extends BaseActivity implements StaffReportContract.View {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.tv_rank)
    TextView mTvRank;
    @BindView(R.id.tv_has_report_count)
    TextView mTvHasReportCount;
    @BindView(R.id.tv_real_report_count)
    TextView mTvRealReportCount;
    @BindView(R.id.tv_left_report_count)
    TextView mTvLeftReportCount;
    @BindView(R.id.rv_report)
    RecyclerView mRvReport;


    List<StaffReportEntity.ResultMessageBean.PlanBean> mReportEntities = new ArrayList<>();
    StaffReportAdapter mReportAdapter;
    StaffPostEntity.ResultMessageBean post;
    AttendanceApi mAttendanceApi;

    StaffReportEntity.ResultMessageBean.DataBean mDataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int initContentView() {
        return R.layout.activity_staff_report;
    }

    @Override
    public void initInjector() {
        post = getIntent().getParcelableExtra("post");
        mAttendanceApi = new AttendanceApi(mContext);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        EventBus.getDefault().register(this);
        mReportAdapter = new StaffReportAdapter(mReportEntities, this);
        mRvReport.setLayoutManager(new LinearLayoutManager(mContext));
        mRvReport.setAdapter(mReportAdapter);

        if (post != null) {
            mTopBar.setTitle(post.getPost());
            fetchPostDetail(post.getId());
        }

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    private void fetchPostDetail(int id) {
        mAttendanceApi.getSignPostDetail(String.valueOf(id))
                .subscribeOn(Schedulers.io())
                .map(new Func1<StaffReportEntity, List<StaffReportEntity.ResultMessageBean.PlanBean>>() {
                    @Override
                    public List<StaffReportEntity.ResultMessageBean.PlanBean> call(StaffReportEntity entity) {
                        mDataBean = entity.getResultMessage().getData();
                        return entity.getResultMessage().getPlan();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<StaffReportEntity.ResultMessageBean.PlanBean>>() {
                    @Override
                    public void onCompleted() {
                        mReportAdapter.notifyDataSetChanged();
                        setReportInfo();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiException) {
//                            ToastUtil.showToast(e.getMessage());
                            showAlert(e.getMessage());
                        }

                    }

                    @Override
                    public void onNext(List<StaffReportEntity.ResultMessageBean.PlanBean> planBeen) {
                        mReportEntities.clear();
                        mReportEntities.addAll(planBeen);
                    }
                });
    }


    private void setReportInfo() {
        if (mDataBean != null) {
            mTvRank.setText(String.format("班次：%1s", mDataBean.getPostsetting().getPostsetting_name()));
            mTvRealReportCount.setText(String.format("实际报岗次数：%1s", mDataBean.getActualpostnumber()));
            mTvHasReportCount.setText(String.format("应报岗次数：%1s", mDataBean.getPostnumber()));
            mTvLeftReportCount.setText(String.format("未报岗次数：%1s", mDataBean.getRemaining()));
        } else {
            LogUtil.e("mDataBean is null");
        }
    }


    @Override
    public void onCheckInfoClick(StaffReportEntity.ResultMessageBean.PlanBean planBean) {
        Intent intent = new Intent(mContext, StaffReportInfoActivity.class);
        intent.putExtra("reportinfo", planBean);
        intent.putExtra("datainfo", mDataBean);
        mContext.startActivity(intent);
    }

    @Override
    public void onTakePhotoClick(StaffReportEntity.ResultMessageBean.PlanBean planBean) {
        Intent intent = new Intent(mContext, AttendanceTokePhotoActivity.class);
        intent.putExtra("reportinfo", planBean);
        startActivityForResult(intent, AttendanceTokePhotoActivity.REQUEST_CODE);
    }

    @Override
    public StaffReportEntity.ResultMessageBean.DataBean fetchData() {
        return mDataBean;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AttendanceTokePhotoActivity.REQUEST_CODE && resultCode == AttendanceTokePhotoActivity.RESULT_CODE) {
            String path = data.getStringExtra("path");
            StaffReportEntity.ResultMessageBean.PlanBean planBean = data.getParcelableExtra("reportinfo");
            submitReport(path, planBean);
        }
    }

    private void submitReport(String path, StaffReportEntity.ResultMessageBean.PlanBean planBean) {
        Intent intent = new Intent(mContext, SubmitReportActivity.class);
        intent.putExtra("photo", path);
        intent.putExtra("postsettingid", String.valueOf(post.getId()));
        intent.putExtra("reportinfo", planBean);
        intent.putExtra("datainfo", mDataBean);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSubmit(ReportSubmitEvent event) {
        fetchPostDetail(post.getId());
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    private void showAlert(String msg) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext, android.app.AlertDialog.THEME_HOLO_LIGHT);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.create().show();
    }


}
